// renderer/api-wrapper.ts
import { dialog } from 'electron';

type FileOperationResult<T = string> = {
  success: boolean;
  data?: T;
  error?: string;
};

class ElectronAPIWrapper {
  private static get api(): IElectronAPI {
    if (!window.electronAPI) {
      throw new Error('Electron API not available in this environment');
    }
    return window.electronAPI;
  }

  /**
   * 读取文件内容
   * @param path 文件路径
   * @returns 文件内容或错误信息
   */
  static async readFile(path: string): Promise<FileOperationResult> {
    try {
      const result = await this.api.readFile(path);
      if (!result.success) {
        console.error(`Failed to read file: ${result.error}`);
      }
      return result;
    } catch (error) {
      console.error('Unexpected error reading file:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * 写入文件内容
   * @param path 文件路径
   * @param content 要写入的内容
   */
  static async writeFile(path: string, content: string): Promise<FileOperationResult> {
    try {
      const result = await this.api.writeFile(path, content);
      if (!result.success) {
        console.error(`Failed to write file: ${result.error}`);
      }
      return result;
    } catch (error) {
      console.error('Unexpected error writing file:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * 显示文件选择对话框
   * @param options 对话框选项
   * @returns 用户选择的文件路径
   */
  static async showFileDialog(
    options: Electron.OpenDialogOptions = {
      properties: ['openFile']
    }
  ): Promise<string | null> {
    try {
      const result = await this.api.showDialog(options);
      return result.filePaths[0] || null;
    } catch (error) {
      console.error('Error showing dialog:', error);
      return null;
    }
  }
}

export const electronAPI = ElectronAPIWrapper;
